<!--
 * @Author: your name
 * @Date: 2021-08-16 08:33:47
 * @LastEditTime: 2022-02-28 14:32:21
 * @LastEditors: jgg
 * @Description: In User Settings Edit
 * @FilePath: \yyzxwebd:\hsx\水文局设备运行巡检管理平台\web\src\views\equipmentManage\safeGuardList\add.vue
-->
<template>
    <el-dialog 
        :title="type=='add'?'新增角色':'编辑角色'" 
        :model-value="visible"
        :destroy-on-close="true"
        width="600px"
        :before-close="onCancel"
    >
        <!-- fullscreen -->
        <el-form class="form form_height noScrollbar" ref="form"  :rules="rules" :model="form"  label-width="100px" label-position="right">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="角色名称:" prop="name">
                        <el-input v-model="form.name"  clearable placeholder="请输入角色名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="角色字符串:" prop="code">
                        <el-input v-model="form.code"  clearable placeholder="请输入角色字符串"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="显示顺序:" prop="orderNum">
                        <el-input v-model="form.orderNum" clearable placeholder="请输入显示顺序"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="角色状态:">
                        <el-radio-group v-model="form.status">
                            <el-radio label="0">正常</el-radio>
                            <el-radio label="1">禁用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="描述:">
                    <el-input v-model="form.des" type="textarea" rows="3" clearable placeholder="请输入描述"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="菜单权限:">
                        <el-tree
                            style="height:260px;overflow:auto;"
                            ref="permissionTree"
                            v-loading="loading"
                            :default-expand-all="true"
                            :data="permissions"
                            show-checkbox
                            node-key="id"
                            :props="{label: 'name', children: 'subCategories'}">
                        </el-tree>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="onSubmit" :loading="anniuloading">保 存</el-button>
                <el-button @click="onCancel">取 消</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script>
import { formatTimestamp } from '@/utils/common'
import userApi from '@/api/user'
export default {
    emits: ['onChange'],
    components:{
    },
    props:{
        visible:{
            default:false,
            type: Boolean
        },
        type:{
            default:'add',
            type: String
        },
        item:{
            default:()=>{
                return {}
            },
            type: Object
        }
    },
    data(){
        return {
            loading:false,
            anniuloading:false,
            permissions:[],
            checkedKey:[],
            
            form:{
                status:'0'
                // maintenancePersonId:[1,2,3]
            },
            rules:{
                name: [
                    { required: true, message: '请输入角色名', trigger: ['change','blur'], }
                ],
                code: [
                    { required: true, message: '请输入角色字符串', trigger: ['change','blur'], }
                ],
                orderNum: [
                    { required: true, message: '请输入显示顺序', trigger: ['change','blur'], }
                ],
            },
        }
    },
    watch:{
        visible(newValue){
            if(newValue){
                this.$nextTick(()=>{
                    this.$refs['form'].resetFields()
                })
                this.handleGetData()
                if(this.type == 'edit'){
                    this.form = JSON.parse(JSON.stringify(this.item))
                }
            }else{
                this.$refs['form'].resetFields()
                this.form = {}
            }
        }
    },
    created(){
    },
    methods:{
        // 递归寻找被选中的节点
        findSelectKey(data) {
            if (data.length === 0) return
            data.map(item => {
                // 如果选中且没有子节点 直接push
                for (let i = 0; i < this.form.menuIdList.length; i++) {
                    if(item.id == this.form.menuIdList[i]){
                        if(item.subCategories.length === 0) {
                            this.checkedKey.push(item.id)
                        } else {
                            this.findSelectKey(item.subCategories)
                        }
                    }
                }
            })
        },
        getRoleData(){
            this.loading = true
            userApi.getRoleData({id:this.form.id})
                .then(res => {
                    this.form.menuIdList = res.data.menuIdList
                    this.findSelectKey(this.permissions)
                    this.$refs.permissionTree.setCheckedKeys(this.checkedKey, true)
                    this.loading = false
                })
                .catch(err => {
                    this.loading = false
                    this.$message.error(err.message)
                })
        },
        // 菜单树结构和角色权限匹配
        handleGetData() {
            this.loading = true
            this.checkedKey = []
            this.menuIdList = []
            this.permissions = []
            userApi.cdMenuList()
                .then(res => {
                    this.permissions = res.data
                    if(this.type == 'edit'){
                        this.getRoleData()
                    }
                    this.loading = false
                })
                .catch(err => {
                    this.loading = false
                    this.$message.error(err.message)
                })
        },
        onSubmit(){
            let userInfo = JSON.parse(localStorage.getItem('userInfo'))
            this.$refs['form'].validate((valid) => {
                if (valid) {
                        this.anniuloading = true
                        let halfSelectKey = this.$refs.permissionTree.getHalfCheckedKeys()
                        let selectKey = this.$refs.permissionTree.getCheckedKeys()
                        this.form.menuIdList = [...halfSelectKey,...selectKey]
                        if(this.type == 'add'){
                            userApi.roleSave(this.form).then((res)=>{
                                this.anniuloading = false
                                if(userInfo.roleId === this.item.id) {
                                    this.$store.commit('setPermissions',JSON.stringify(res.data.perms))
                                }
                                this.$emit('onChange',{bool:false,refresh:true})
                            }).catch((err)=>{
                                this.anniuloading = false
                                this.$message.error(err.message)
                            })
                        }else if (this.type == 'edit'){
                            userApi.roleUpdate(this.form).then((res)=>{
                                this.anniuloading = false
                                if(userInfo.roleId === this.item.id) {
                                    this.$store.commit('setPermissions',JSON.stringify(res.data.perms))
                                }
                                this.$emit('onChange',{bool:false,refresh:true})
                                this.$store.commit('setPermissions',JSON.stringify(res.data.perms))
                            }).catch((err)=>{
                                this.anniuloading = false
                                this.$message.error(err.message)
                            })
                        }
                        
                } else {
                    return false
                }
            })
        },
        onCancel(){
            this.$emit('onChange',{bool:false})
        }
    },
}
</script>
<style lang="scss" scoped>
    .form_height{
        max-height: 50vh;
        overflow-y: auto;
    }
    .width100{
        width: 100%;
    }
    ::v-deep.upload_box .el-upload-list__item-preview{
        display: none !important;
    }
    .img_box{
        display: flex;
        flex-wrap: wrap;
        &>div{
            width: 100px;
            height: 100px;
            margin-bottom: 10px;
            margin-right: 10px;
            border: 1px solid #DCDFE6;
            border-radius: 5px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            &:hover{
                .delete_icon{
                    background-color: rgba(0,0,0,0.7);
                    display: flex;
                }
            }
            .delete_icon{
                display: none;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: 0;
                right: 0;
                left: 0;
                bottom: 0;
                color: #fff;
                font-size: 20px;
            }
            img{
                width: 100%;
                height: 100%;
                object-fit: cover;
                
            }
        }
        
    }
</style>